package com.ahdy.controller;

import com.ahdy.entity.MedicationRecord;
import com.ahdy.entity.MedicationStatisticsDTO;
import com.ahdy.service.MedicationRecordService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用药记录管理控制器
 */
@RestController
@RequestMapping("/api/medication-records")
public class MedicationRecordController {

    @Autowired
    private MedicationRecordService medicationRecordService;

    /**
     * 添加用药记录
     *
     * @param record 用药记录实体
     * @return 响应结果
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> addMedicationRecord(@Valid @RequestBody MedicationRecord record) {
        Integer id = medicationRecordService.addMedicationRecord(record);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "添加用药记录成功");
        response.put("data", id);
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }

    /**
     * 更新用药记录
     *
     * @param id     记录ID
     * @param record 用药记录实体
     * @return 响应结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateMedicationRecord(@PathVariable Integer id,
            @Valid @RequestBody MedicationRecord record) {
        record.setId(id);
        int rows = medicationRecordService.updateMedicationRecord(record);

        Map<String, Object> response = new HashMap<>();
        if (rows > 0) {
            response.put("code", 200);
            response.put("message", "更新用药记录成功");
        } else {
            response.put("code", 404);
            response.put("message", "用药记录不存在");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 删除用药记录
     *
     * @param id 记录ID
     * @return 响应结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteMedicationRecord(@PathVariable Integer id) {
        int rows = medicationRecordService.deleteMedicationRecord(id);

        Map<String, Object> response = new HashMap<>();
        if (rows > 0) {
            response.put("code", 200);
            response.put("message", "删除用药记录成功");
        } else {
            response.put("code", 404);
            response.put("message", "用药记录不存在");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 根据ID查询用药记录
     *
     * @param id 记录ID
     * @return 响应结果
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getMedicationRecordById(@PathVariable Integer id) {
        MedicationRecord record = medicationRecordService.getMedicationRecordById(id);

        Map<String, Object> response = new HashMap<>();
        if (record != null) {
            response.put("code", 200);
            response.put("message", "获取用药记录成功");
            response.put("data", record);
            return ResponseEntity.ok(response);
        } else {
            response.put("code", 404);
            response.put("message", "用药记录不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

    /**
     * 根据任务ID查询用药记录
     *
     * @param taskId 任务ID
     * @return 响应结果
     */
    @GetMapping("/task/{taskId}")
    public ResponseEntity<Map<String, Object>> getMedicationRecordByTaskId(@PathVariable Integer taskId) {
        MedicationRecord record = medicationRecordService.getMedicationRecordByTaskId(taskId);

        Map<String, Object> response = new HashMap<>();
        if (record != null) {
            response.put("code", 200);
            response.put("message", "获取用药记录成功");
            response.put("data", record);
            return ResponseEntity.ok(response);
        } else {
            response.put("code", 404);
            response.put("message", "用药记录不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

    /**
     * 根据用户ID查询用药记录列表
     *
     * @param userId 用户ID
     * @return 响应结果
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getMedicationRecordsByUserId(@PathVariable Integer userId) {
        List<MedicationRecord> records = medicationRecordService.getMedicationRecordsByUserId(userId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取用户用药记录列表成功");
        response.put("data", records);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据用户ID和日期范围查询用药记录列表
     *
     * @param userId    用户ID
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 响应结果
     */
    @GetMapping("/user/{userId}/date-range")
    public ResponseEntity<Map<String, Object>> getMedicationRecordsByUserIdAndDateRange(
            @PathVariable Integer userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        List<MedicationRecord> records = medicationRecordService.getMedicationRecordsByUserIdAndDateRange(userId,
                startDate, endDate);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取指定日期范围用药记录成功");
        response.put("data", records);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据用户ID删除所有用药记录
     *
     * @param userId 用户ID
     * @return 响应结果
     */
    @DeleteMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> deleteMedicationRecordsByUserId(@PathVariable Integer userId) {
        int rows = medicationRecordService.deleteMedicationRecordsByUserId(userId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "删除用户所有用药记录成功");
        response.put("data", rows);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据任务ID删除用药记录
     *
     * @param taskId 任务ID
     * @return 响应结果
     */
    @DeleteMapping("/task/{taskId}")
    public ResponseEntity<Map<String, Object>> deleteMedicationRecordsByTaskId(@PathVariable Integer taskId) {
        int rows = medicationRecordService.deleteMedicationRecordsByTaskId(taskId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "删除任务相关用药记录成功");
        response.put("data", rows);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取用药依从性统计
     *
     * @param userId    用户ID
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 响应结果
     */
    @GetMapping("/statistics/compliance/{userId}")
    public ResponseEntity<Map<String, Object>> getMedicationComplianceStatistics(
            @PathVariable Integer userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        List<MedicationStatisticsDTO> statistics = medicationRecordService.getMedicationComplianceStatistics(userId,
                startDate, endDate);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取用药依从性统计成功");
        response.put("data", statistics);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取延迟服药统计
     *
     * @param userId 用户ID
     * @param days   天数
     * @return 响应结果
     */
    @GetMapping("/statistics/delay/{userId}")
    public ResponseEntity<Map<String, Object>> getDelayStatistics(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "30") Integer days) {

        List<Map<String, Object>> statistics = medicationRecordService.getDelayStatistics(userId, days);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取延迟服药统计成功");
        response.put("data", statistics);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取用药记录详情（包含药物信息）
     *
     * @param userId 用户ID
     * @param limit  限制条数
     * @return 响应结果
     */
    @GetMapping("/details/{userId}")
    public ResponseEntity<Map<String, Object>> getMedicationRecordDetailsWithMedication(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "10") Integer limit) {

        List<Map<String, Object>> recordDetails = medicationRecordService
                .getMedicationRecordDetailsWithMedication(userId, limit);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取用药记录详情成功");
        response.put("data", recordDetails);
        return ResponseEntity.ok(response);
    }
}
